import 'package:demo202112/utils/common_appbar.dart';
import 'package:flutter/material.dart';

/// @Author wywinstonwy
/// @Date 2022/1/19 10:46 下午
/// @Description:

class MyScrollController extends StatefulWidget {
  const MyScrollController({Key? key}) : super(key: key);

  @override
  _MyScrollControllerState createState() => _MyScrollControllerState();
}

class _MyScrollControllerState extends State<MyScrollController> {
  final ScrollController _controller = ScrollController();
  bool showToTopBtn = false; //是否显示“返回到顶部”按钮

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    //监听滚动事件，打印滚动位置
    _controller.addListener(() {
      //打印滚动位置
      print(_controller.offset);
      if (_controller.offset < 1000 && showToTopBtn) {
        setState(() {
          showToTopBtn = false;
        });
      } else if (_controller.offset >= 1000 && showToTopBtn == false) {
        setState(() {
          showToTopBtn = true;
        });
      }
    });
  }
  @override
  void dispose() {
    //为了避免内存泄露，需要调用_controller.dispose
    _controller.dispose();
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: getAppBar('滚动监听以及控制'),
      body: _buildScollBar(),
      floatingActionButton: showToTopBtn==false?null:FloatingActionButton(
        onPressed: (){
          //返回到顶部时候执行动画
          _controller.animateTo(0, duration: const Duration(milliseconds: 200), curve: Curves.easeIn);
        },
        child: const Icon(Icons.arrow_upward),),
    );
  }
  _buildScollBar(){
    return Scrollbar(
        child: ListView.builder(
          controller: _controller,
            itemCount: 100,
            itemExtent: 44,
            itemBuilder: (context,index){
          return ListTile(title: Text('$index'),);
        })
    );
  }
}
